package com.example.development.jvmStudy.oom;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

//import org.springframework.cglib.proxy.Enhancer;
//import org.springframework.cglib.proxy.MethodInterceptor;
//import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;


/**
 * @author: vince_zww
 * @date: 2020/8/25 11:01
 * @desceription: 模拟Metaspace内存溢出
 *
 * JVM运行参数记得必须设置：-XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m
 */
public class MetaspaceOOM {
    public static void main(String[] args) {
        long counter = 0;
        while (true){
            System.out.println("目前创建了"+(++counter)+"个Car类的子类");
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(Car.class);
            enhancer.setUseCache(false);
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    System.out.println("进入拦截处理代码");
                    if (method.getName().equals("run")) {
                        System.out.println("启动汽车之前，先进行自动的安全检查...");
                        return methodProxy.invokeSuper(o,objects);
                    }else {
                        return methodProxy.invokeSuper(o,objects);
                    }
                }
            });
            Car car = (Car) enhancer.create();
            car.run();
        }
    }

    static class Car{
        public void run(){
            System.out.println("汽车启动，开始行使....");
        }
    }
}
